<template>
  <div class="root-container" v-loading="isLoading">
    <div class="bar-container">
      <el-form inline>
        <el-form-item>
          <el-radio-group v-model="rangeType" @change="handleRangeTypeChange">
            <el-radio-button value="lastMonth">上月</el-radio-button>
            <el-radio-button value="thisMonth">本月</el-radio-button>
            <el-radio-button value="lastWeek">上周</el-radio-button>
            <el-radio-button value="thisWeek">本周</el-radio-button>
            <el-radio-button value="yesterday">昨日</el-radio-button>
            <el-radio-button value="today">今日</el-radio-button>
            <el-radio-button value="custom">自定义</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="range"
            type="daterange"
            range-separator="To"
            start-placeholder="Start date"
            end-placeholder="End date"
            :disabled="rangeType != 'custom'"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doQuery">
            <span v-if="rangeType == 'custom'">
              <el-icon><search /></el-icon>
              <span>查询</span>
            </span>
            <span v-else>
              <el-icon><Refresh /></el-icon>
              <span>刷新</span>
            </span>
          </el-button>
          <el-button
            type="success"
            @click="doExport"
            :disabled="!sourceData"
            v-if="false"
          >
            <span>导出</span>
          </el-button>
        </el-form-item>
        <el-form-item v-if="tableData && tableData.length > 0">
          <el-checkbox-group v-model="categories">
            <el-checkbox-button value="M">批次</el-checkbox-button>
            <el-checkbox-button value="G">通航</el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-if="tableData && tableData.length > 0">
          <el-radio-group v-model="activeTab" @change="handleTabChange">
            <el-radio-button value="details">明细</el-radio-button>
            <el-radio-button value="summary">统计</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="tableData && tableData.length > 0" class="brif-container">
      <b>数据概要</b>
      <span>记录数：{{ briefData.recordCount }}条</span>
      <span> 总架次：{{ briefData.flightCount }}架 </span>
      <span> 总时长：{{ briefData.duration }}h </span>
    </div>
    <div v-else class="brif-container">
      <b>数据概要</b>
      <span>暂无数据</span>
    </div>
    <div class="tab-container">
      <transition name="el-fade-in-linear" mode="out-in">
        <el-table
          :data="tableDataFiltered"
          :height="tableHeight"
          v-if="showTable && activeTab == 'details'"
        >
          <el-table-column prop="number" label="#" min-width="60px" />
          <el-table-column prop="unit" label="单位" min-width="120px" />
          <el-table-column prop="callsign" label="呼号" min-width="120px" />
          <el-table-column prop="category" label="类型" min-width="80px">
            <template #default="scope">
              <el-tag type="info" v-if="scope.row.category == 'M'">批次</el-tag>
              <el-tag type="primary" v-if="scope.row.category == 'G'"
                >通航</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="startTime"
            label="开始时间"
            min-width="180px"
          />
          <el-table-column label="结束时间" min-width="180px">
            <template #default="scope">
              <el-text type="warning" v-if="scope.row.endTime == null"
                >未结束</el-text
              >
              <span v-else>{{ scope.row.endTime }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="时长" min-width="80px">
            <template #default="scope">
              <span>{{ scope.row.duration }} h</span>
            </template>
            <!-- <template #default="scope">
              <el-text type="warning" v-if="scope.row.endTime == null"
                >{{
                  dayjs().diff(scope.row.startTime, "hour", true).toFixed("1")
                }}h</el-text
              >
              <span v-else
                >{{
                  dayjs(scope.row.endTime)
                    .diff(scope.row.startTime, "hour", true)
                    .toFixed("1")
                }}h</span
              >
            </template> -->
          </el-table-column>
          <el-table-column label="架次" min-width="80px">
            <template #default="scope">
              <span type="warning" v-if="scope.row.flightCount == 0">未知</span>
              <span v-else>{{ scope.row.flightCount }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="80px">
            <template #default="scope">
              <el-button
                v-if="scope.row.endTime != null"
                type="primary"
                @click="openEdit(scope.row)"
                link
              >
                <el-icon><Edit /></el-icon>
                <span>编辑</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-table
          v-else-if="showTable && activeTab == 'summary'"
          :data="summaryDataFiltered"
          :height="tableHeight"
        >
          <el-table-column prop="unit" label="#" min-width="60px" fixed>
            <template #default="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" min-width="120px" fixed />
          <el-table-column label="类型" min-width="80px">
            <template #default="scope">
              <el-tag type="info" v-if="scope.row.category == 'M'">批次</el-tag>
              <el-tag type="primary" v-if="scope.row.category == 'G'"
                >通航</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="count" label="架次" min-width="80px" />
          <el-table-column prop="times" label="次数" min-width="80px" />
          <el-table-column prop="days" label="天数" min-width="80px" />
          <el-table-column prop="hours" label="小时" min-width="80px" />
          <el-table-column
            prop="earliestStartTime"
            label="最早开飞"
            min-width="180px"
          />
          <el-table-column
            prop="latestStartTime"
            label="最晚开飞"
            min-width="180px"
          />
          <el-table-column
            prop="earliestEndTime"
            label="最早结束"
            min-width="180px"
          />
          <el-table-column
            prop="latestEndTime"
            label="最晚结束"
            min-width="180px"
          />
        </el-table>
      </transition>
    </div>
    <ToolboxWindow
      :title="itemEdited ? `编辑 ${itemEdited.callsign} 的记录` : ''"
      :width="360"
      :show="showEditor"
      @close="cancelEdit()"
    >
      <el-form v-if="itemEdited" label-width="80px">
        <el-form-item label="开始时间">
          <el-time-picker
            v-model="itemEdited.startTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="HH:mm:ss"
            :clearable="false"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-time-picker
            v-model="itemEdited.endTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="HH:mm:ss"
            :clearable="false"
          />
        </el-form-item>
        <el-form-item label="实际架次">
          <el-input-number
            v-model="itemEdited.flightCount"
            :min="0"
            :max="9999"
            :precision="0"
            @change="handleFlightCountChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveEdit()">保存</el-button>
          <el-button type="primary" link @click="cancelEdit()">取消</el-button>
        </el-form-item>
      </el-form>
    </ToolboxWindow>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, h, nextTick } from "vue";
import dayjs from "dayjs";
import useCommonStore from "@/store/common.js";
import handleQuery from "./handleQuery.js";
import handleSave from "./handleSave.js";
import ToolboxWindow from "@/components/ToolboxWindow";
import isSameOrAfter from "dayjs/plugin/isSameOrAfter";
import isSameOrBefore from "dayjs/plugin/isSameOrBefore";
import updateLocale from "dayjs/plugin/updateLocale";

// 注册插件
dayjs.extend(isSameOrAfter);
dayjs.extend(isSameOrBefore);
dayjs.extend(updateLocale);
dayjs.updateLocale("en", {
  weekStart: 1,
});

const commonStore = useCommonStore();
const isLoading = ref(false);

const rangeType = ref("today");
const range = ref([new Date(), new Date()]);
const categories = ref(["G"]);
const showTable = ref(true);
const activeTab = ref("details");

const tableData = ref([]);

const tableDataFiltered = computed(() =>
  tableData.value
    .filter((item) => categories.value.includes(item.category))
    .map((item) => ({
      ...item,
      duration: parseFloat(
        item.endTime == null
          ? dayjs().diff(item.startTime, "hour", true).toFixed(2)
          : dayjs(item.endTime)
              .diff(dayjs(item.startTime), "hour", true)
              .toFixed(2)
      ),
    }))
);

const tableHeight = computed(() => commonStore.clientHeight - 200);

const summaryData = ref([]);

const summaryDataFiltered = computed(() =>
  summaryData.value.filter((item) => categories.value.includes(item.category))
);

const handleTabChange = (value) => {
  if (value != "details") {
    cancelEdit();
  }
};

const handleRangeTypeChange = (value) => {
  switch (value) {
    case "lastMonth":
      range.value = [
        dayjs().subtract(1, "month").startOf("month").toDate(),
        dayjs().subtract(1, "month").endOf("month").toDate(),
      ];
      doQuery();
      break;
    case "thisMonth":
      range.value = [
        dayjs().startOf("month").toDate(),
        dayjs().endOf("month").toDate(),
      ];
      doQuery();
      break;
    case "lastWeek":
      range.value = [
        dayjs().subtract(1, "week").startOf("week").toDate(),
        dayjs().subtract(1, "week").endOf("week").toDate(),
      ];
      doQuery();
      break;
    case "thisWeek":
      range.value = [
        dayjs().startOf("week").toDate(),
        dayjs().endOf("week").toDate(),
      ];
      doQuery();
      break;
    case "yesterday":
      range.value = [
        dayjs().subtract(1, "day").toDate(),
        dayjs().subtract(1, "day").toDate(),
      ];
      doQuery();
      break;
    case "today":
      range.value = [dayjs().toDate(), dayjs().toDate()];
      doQuery();
      break;
    default:
  }
};

const doQuery = () => {
  isLoading.value = true;
  handleQuery(range.value)
    .then((content) => {
      tableData.value = content;
      summaryData.value = doSummary(content);
    })
    .finally(() => {
      isLoading.value = false;
    });
};

const doExport = () => {};

const itemEdited = ref();
const showEditor = ref(false);
const openEdit = (item) => {
  showEditor.value = true;
  itemEdited.value = JSON.parse(JSON.stringify(item));
  // console.log("openEdit", item);
  /*
  {
    "number": 1,
    "unit": "川协",
    "callsign": "川协",
    "category": "G",
    "startTime": "2025-07-26 21:48:05",
    "endTime": null,
    "flightCount": 0
}
    */
};

const cancelEdit = () => {
  showEditor.value = false;
  itemEdited.value = null;
};
const saveEdit = () => {
  isLoading.value = true;
  showTable.value = false;
  handleSave(itemEdited.value)
    .then(() => {
      for (let i = 0; i < tableData.value.length; i++) {
        if (tableData.value[i].number == itemEdited.value.number) {
          tableData.value[i] = itemEdited.value;
        }
      }
    })
    .finally(() => {
      showEditor.value = false;
      itemEdited.value = null;
      isLoading.value = false;
      showTable.value = true;
    });
};

const handleFlightCountChange = (currentValue, oldValue) => {
  if (!currentValue || currentValue == "") {
    itemEdited.value.flightCount = oldValue;
  } else {
    itemEdited.value.flightCount = parseInt(currentValue);
  }
};

const doSummary = (content) => {
  const result = {};
  if (content && content.length > 0) {
    for (let i = 0; i < content.length; i++) {
      const row = content[i];
      // new unit target
      if (!result[row.unit]) {
        result[row.unit] = {
          unit: row.unit,
          category: row.category,
          count: 0,
          times: 0,
          hours: 0,
          days: 0,
          dates: [],
          earliestStartTime: "",
          earliestEndTime: "",
          latestStartTime: "",
          latestEndTime: "",
        };
      }
      const target = result[row.unit];
      target.count += row.flightCount;
      target.times++;
      const startDay = dayjs(row.startTime);
      const endDay = row.endTime ? dayjs(row.endTime) : dayjs();
      const execDate = startDay.format("YYYY-MM-DD");
      target.hours += endDay.diff(startDay, "hour", true);
      if (!target.dates.includes(execDate)) {
        target.dates.push(execDate);
        target.days++;
      }
      // 最早 开始时间
      if (
        target.earliestStartTime == "" ||
        startDay.isBefore(target.earliestStartTime)
      ) {
        target.earliestStartTime = row.startTime;
      }
      // 最晚 开始时间
      if (
        target.latestStartTime == "" ||
        startDay.isAfter(target.latestStartTime)
      ) {
        target.latestStartTime = row.startTime;
      }
      // 最早 结束时间
      if (
        target.earliestEndTime == "" ||
        endDay.isBefore(target.earliestEndTime)
      ) {
        target.earliestEndTime = row.endTime;
      }
      // 最晚 结束时间
      if (target.latestEndTime == "" || endDay.isAfter(target.latestEndTime)) {
        target.latestEndTime = row.endTime;
      }
    }
    const resultArray = Object.keys(result).map((key) => {
      result[key].hours = Math.round(result[key].hours * 10) / 10;
      return result[key];
    });
    return resultArray;
  } else {
    return [];
  }
};

const briefData = computed(() => {
  if (!tableDataFiltered.value || tableDataFiltered.value.length == 0)
    return {
      recordCount: 0,
      flightCount: 0,
      duration: 0,
    };
  return {
    recordCount: tableDataFiltered.value.length,
    flightCount: tableDataFiltered.value.reduce(
      (sum, item) => sum + (item.count || 0),
      0
    ),
    duration: tableDataFiltered.value.reduce(
      (sum, item) => sum + item.duration,
      0
    ),
  };

  return data;
});

onMounted(() => {
  doQuery();
});
</script>

<style scoped>
.bar-container {
  margin: 16px 24px;
}
.root-container {
  padding: 0;
}
.tab-container {
  margin: 16px 24px;
}

.brif-container {
  border-radius: 8px;
  padding: 4px 16px;
  margin: 8px 16px;
  display: flex;
  align-items: center;
  font-size: 14px;
  /* border: 1px solid #8884; */
  /* background-color: #8884; */
  /* color: var(--el-text-color-regular); */
  /* border: 1px solid var(--el-color-primary); */
  background-color: var(--el-color-primary-light-7);
  color: var(--el-color-primary);
  /* box-shadow: 0 4px 8px #0004; */
}

.brif-container > * {
  margin-right: 32px;
}
</style>
